import { Injectable } from '@nestjs/common';
import { InjectModel } from '@nestjs/mongoose';
import { Carwash } from 'src/schemas/carwash/carwash.interface';
import { Model } from 'mongoose';
import { CarwashDto } from 'src/dto/carwash.dto';
import { CarwashesPaginationDto } from 'src/dto/carwashes-pagination.dto';

@Injectable()
export class CarwashesService {
  constructor(
    @InjectModel('Carwash') private readonly carwashModel: Model<Carwash>,
  ) {}

  /**
   * 创建一个洗车点
   * @param carwashDto 洗车点信息
   */
  create(carwashDto: CarwashDto) {
    const createdCarwash = new this.carwashModel(carwashDto);
    return createdCarwash.save();
  }

  /**
   * 通过编号删除洗车点
   * @param _id _id
   */
  deleteById(_id: string) {
    return this.carwashModel.deleteOne({ _id });
  }

  /**
   * 通过 _id 更新洗车点信息
   * @param _id _id
   * @param carwashDto 洗车点信息
   */
  updateById(_id: string, carwashDto: CarwashDto) {
    return this.carwashModel.updateOne({ _id }, carwashDto);
  }

  /**
   * 查询一些洗车点
   * @param staffsPaginationDto 查询条件
   */
  find(carwashesPaginationDto: CarwashesPaginationDto) {
    const { pageIndex, pageSize, keyword } = carwashesPaginationDto;
    let conditions = {};
    if (keyword !== '') {
      conditions = {
        city: { $all: keyword.split(',') },
      };
    }

    return this.carwashModel
      .find(conditions, '-__v')
      .sort({ _id: -1 })
      .skip((pageIndex - 1) * pageSize)
      .limit(pageSize);
  }

  /**
   * 获得洗车点的总数
   * @param staffsPaginationDto 查询条件
   */
  count(carwashesPaginationDto: CarwashesPaginationDto) {
    const { keyword } = carwashesPaginationDto;
    const reg = new RegExp(keyword, 'i');
    const conditions = {
      $or: [{ city: { $regex: reg } }],
    };

    return this.carwashModel.find(conditions).countDocuments();
  }
}
